package com.hexseek.libretvcloud.controller;

import com.hexseek.libretvcloud.model.History;
import com.hexseek.libretvcloud.model.R;
import com.hexseek.libretvcloud.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
/**
 * @author zhougb9
 * @version 1.0.0
 * @description TODO 搜索历史
 * @date 2025/5/14 17:54
 * @title HistoryController
 */

@RestController
@RequestMapping("/api/history")
public class HistoryController {


    @Autowired
    HistoryService historyService;

    // 获取最近搜索历史
    @GetMapping("getHistory")
    public R<?> getHistory(
            @CookieValue(value = "userId", required = false) String userId) {

        if (userId == null || userId.isEmpty()) {
            userId = historyService.generateTempUserId();
        }

        List<History> historyList = historyService.getRecentSearches(userId);

        return R.ok(historyList);
    }

    // 保存搜索记录
    @PostMapping("addHistory")
    public R<?> addHistory(
            @RequestBody Map<String, String> request,
            @CookieValue(value = "userId", required = false) String userId) {

        String keyword = request.get("keyword");
        if (keyword == null || keyword.trim().isEmpty()) {
            R.fail("关键词不能为空");
        }


        historyService.saveSearchHistory(keyword, userId);

        return R.ok();
    }

    // 清除搜索记录
    @DeleteMapping("deleteHistory")
    public R<?> deleteHistory(
            @CookieValue(value = "userId", required = false) String userId) {

        if (userId == null || userId.isEmpty()) {
            R.fail("用户ID缺失");
        }

        historyService.clearSearchHistory(userId);
        return R.ok("搜索历史已清除");
    }
}
